import java.util.*;
import javax.jms.*;

public class MDBranchProducer{
    /*-----------------------------------------------------------------------
     * Parameters
     *----------------------------------------------------------------------*/

    String serverUrl = null;
    String userName = null;
    String password = null;
    String name = "update.productInventory";
    Vector data = new Vector();
    boolean useTopic = true;

    /*-----------------------------------------------------------------------
     * Variables
     *----------------------------------------------------------------------*/
    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    Destination replyDestination = null; //for request-reply
    MessageConsumer replyConsumer; //for request-reply

    public MDBranchProducer(String[] args) {
        parseArgs(args);

        try {
            tibjmsUtilities.initSSLParams(serverUrl, args);
        }
        catch (JMSSecurityException e) {
            System.err.println("JMSSecurityException: " + e.getMessage() + ", provider=" + e.getErrorCode());
            e.printStackTrace();
            System.exit(0);
        }

        /* print parameters */
        System.err.println("\n------------------------------------------------------------------------");
        System.err.println("MDBranchProducer");
        System.err.println("------------------------------------------------------------------------");
        System.err.println("Server....................... " + ((serverUrl != null) ? serverUrl : "localhost"));
        System.err.println("User......................... " + ((userName != null) ? userName : "(null)"));
        System.err.println("Destination.................. " + name);
        System.err.println("Message Text................. ");
        for (int i = 0; i < data.size(); i++) {
            System.err.println(data.elementAt(i));
        }
        System.err.println("------------------------------------------------------------------------\n");

        try {
            TextMessage msg;
            int i;

            if (data.size() == 0) {
                System.err.println("***Error: must specify at least one message text\n");
                usage();
            }

            System.err.println("Publishing to destination '" + name + "'\n");

            ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);

            connection = factory.createConnection(userName, password);

            

            /* create the session */
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            /* create the destination */
           if (useTopic) {
                destination = session.createTopic(name);
           } else {
                destination = session.createQueue(name);
           }

            /* create the producer */
            msgProducer = session.createProducer(destination); //changed for request-reply
            replyConsumer = session.createConsumer(replyDestination); //for request-reply
            //replyConsumer.setMessageListener(this);

            /* start the connection */
            connection.start();

            /* publish messages */
            for (i = 0; i < data.size(); i++) {
                /* create text message */
                msg = session.createTextMessage();

                /* set message text */
                msg.setText((String) data.elementAt(i));
                msg.setJMSReplyTo(replyDestination); //for request-reply

                /* publish message */
                msgProducer.send(msg);   //changed for request-reply

                System.err.println("Published message: " + data.elementAt(i));
                System.out.println("Sent request");
                System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
                System.out.println("\tMessage ID: " + msg.getJMSMessageID());
                System.out.println("\tCorrel. ID: " + msg.getJMSCorrelationID());
                System.out.println("\tReply to:   " + msg.getJMSReplyTo());
                System.out.println("\tContents:   " + msg.getText());
            }

            // Send a request and wait for a reply. Code also can be added to time-out the wait
            
            Message reply = null;
            int count = 0;
            while(true){
                reply = replyConsumer.receive(1000);
                if(reply==null){
                    break;
                }else{
                    onMessage(reply);
                }
                count++;
                System.out.println(count);
                
            }

            System.out.println("Replies have been received...");

            // Process the reply.
            //printMsg(reply);
            //onMessage(reply);

            connection.close();

        }
        catch (JMSException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    public void onMessage(Message msg){
        try{
            if (msg instanceof TextMessage) {
                TextMessage replyMessage = (TextMessage) msg;
                System.out.println("Received reply ");
                System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
                System.out.println("\tMessage ID: " + replyMessage.getJMSMessageID());
                System.out.println("\tCorrel. ID: " + replyMessage.getJMSCorrelationID());
                System.out.println("\tReply to:   " + replyMessage.getJMSReplyTo());
                System.out.println("\tContents:   " + replyMessage.getText());
            } else {
                System.out.println("Invalid message detected");
                System.out.println("\tType:       " + msg.getClass().getName());
                System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
                System.out.println("\tMessage ID: " + msg.getJMSMessageID());
                System.out.println("\tCorrel. ID: " + msg.getJMSCorrelationID());
                System.out.println("\tReply to:   " + msg.getJMSReplyTo());

             msg.setJMSCorrelationID(msg.getJMSMessageID());
            }
        }catch(JMSException ex){
        }
    }

    /*-----------------------------------------------------------------------
    * usage
    *----------------------------------------------------------------------*/
    private void usage() {
        System.err.println("\nUsage: java tibjmsMsgProducer [options] [ssl options]");
        System.err.println("                                <message-text-1>");
        System.err.println("                                [<message-text-2>] ...");
        System.err.println("\n");
        System.err.println("   where options are:");
        System.err.println("");
        System.err.println("   -server   <server URL>  - EMS server URL, default is local server");
        System.err.println("   -user     <user name>   - user name, default is null");
        System.err.println("   -password <password>    - password, default is null");
        System.err.println("   -topic    <topic-name>  - topic name, default is \"topic.sample\"");
        System.err.println("   -queue    <queue-name>  - queue name, no default");
        System.err.println("   -help-ssl                 - help on ssl parameters");
        System.exit(0);
    }

    /*-----------------------------------------------------------------------
     * parseArgs
     *----------------------------------------------------------------------*/
    void parseArgs(String[] args) {
        int i = 0;

        while (i < args.length) {
            if (args[i].compareTo("-server") == 0) {
                if ((i + 1) >= args.length) usage();
                serverUrl = args[i + 1];
                i += 2;
            } else if (args[i].compareTo("-topic") == 0) {
                if ((i + 1) >= args.length) usage();
                name = args[i + 1];
                i += 2;
            } else if (args[i].compareTo("-queue") == 0) {
                if ((i + 1) >= args.length) usage();
                name = args[i + 1];
                i += 2;
                useTopic = false;
            } else if (args[i].compareTo("-user") == 0) {
                if ((i + 1) >= args.length) usage();
                userName = args[i + 1];
                i += 2;
            } else if (args[i].compareTo("-password") == 0) {
                if ((i + 1) >= args.length) usage();
                password = args[i + 1];
                i += 2;
            } else if (args[i].compareTo("-help") == 0) {
                usage();
            } else if (args[i].compareTo("-help-ssl") == 0) {
                tibjmsUtilities.sslUsage();
            } else if (args[i].startsWith("-ssl")) {
                i += 2;
            } else {
                data.addElement(args[i]);
                i++;
            }
        }
    }

    /*-----------------------------------------------------------------------
     * main
     *----------------------------------------------------------------------*/
    public static void main(String[] args) {
        String txt = args[0];
        String[] _args = {"-topic", "t.request.b", txt};
        MDBranchProducer t = new MDBranchProducer(_args);
    }

    public void printMsg(Message msg) throws JMSException {
                if (msg instanceof TextMessage) {
            TextMessage replyMessage = (TextMessage) msg;
            System.out.println("Received reply ");
            System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
            System.out.println("\tMessage ID: " + replyMessage.getJMSMessageID());
            System.out.println("\tCorrel. ID: " + replyMessage.getJMSCorrelationID());
            System.out.println("\tReply to:   " + replyMessage.getJMSReplyTo());
            System.out.println("\tContents:   " + replyMessage.getText());
        } else {
            System.out.println("Invalid message detected");
            System.out.println("\tType:       " + msg.getClass().getName());
            System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
            System.out.println("\tMessage ID: " + msg.getJMSMessageID());
            System.out.println("\tCorrel. ID: " + msg.getJMSCorrelationID());
            System.out.println("\tReply to:   " + msg.getJMSReplyTo());

            msg.setJMSCorrelationID(msg.getJMSMessageID());

        }
    }
}

